//
//  HTTruckTypeView.m
//  TruckDriver
//
//  Created by Ting Han on 2017/10/10.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTTruckTypeView.h"
#import "HTTruckCollectionCell.h"
#import "HTHeaderCollectionView.h"
#import "HTTextFieldFooterView.h"
#import "UIView+Layout.h"

#define NUMBERS @"0123456789.\n"

@interface HTTruckTypeView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHeight;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;

@property (nonatomic,strong) NSArray *headerData;

//数据处理
@property (nonatomic,strong) NSDictionary *plistData;
@property (nonatomic,strong) NSMutableArray *lengthsData;
@property (nonatomic,strong) NSMutableArray *truckTypesData;
@property (nonatomic,strong) NSMutableArray *goodsTypeData;

@property (nonatomic,assign) BOOL isLengthOpen;

@property (nonatomic,weak) UITextField *textField;
@property (nonatomic,assign) CGFloat off;
@end

@implementation HTTruckTypeView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    self = [[[NSBundle mainBundle] loadNibNamed:@"HTTruckTypeView" owner:self options:nil] lastObject];
    if (self) {
        self.frame = frame;
        [self setupSubs];
        [self reloadInitData];
        [self reloadContentData];
        [self notifi];
    }
    return self;
}

- (void)notifi{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(keyboardWillShowOrHide:) name:UIKeyboardWillShowNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(keyboardWillShowOrHide:) name:UIKeyboardWillHideNotification object:nil];
     [defaultCenter addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardDidHideNotification object:nil];
    
}
//所有手势
- (void)setupGesture{
    //点击空白处
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
    [self.bottomView addGestureRecognizer:tap];

}
- (void)tapGesture:(UITapGestureRecognizer *)sender{

    //dissmiss remove
    if (self.blockCallBack) {
        self.blockCallBack();
    }
    
}
- (void)setupSubs{
    self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
    [self setupGesture];
    [self.flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    CGFloat width = (kHTScreenWidth - 50)/4.0;
    self.flowLayout.itemSize = CGSizeMake(width, kWidth(30));
    self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 5, 10);
    self.flowLayout.minimumLineSpacing = 15;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HTTruckCollectionCell" bundle:nil] forCellWithReuseIdentifier:TruckCollectionCell];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HTHeaderCollectionView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderCollectionView];
     [self.collectionView registerNib:[UINib nibWithNibName:@"HTTextFieldFooterView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:TextFieldFooter];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;

}
#pragma mark --- 数据处理
- (void)reloadContentData{
    //row 数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Trucks" ofType:@"plist"];
    self.plistData =[NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *GoodsType =  self.plistData[@"GoodsType"];
    NSArray *lengths =  self.plistData[@"TruckLength"];
    NSArray *truckType =  self.plistData[@"TruckType"];
    //车长
    if (self.selectedLengths.count <= 0) {//没有历史数据
         _isLengthOpen = NO;
        [self loadDataUnfold:NO AimData:self.lengthsData WithInitialData:lengths];
        [self.selectedLengths addObject:self.lengthsData.firstObject];
    }else{//有历史数据
        _isLengthOpen = YES;
        [self loadDataUnfold:YES AimData:self.lengthsData WithInitialData:lengths];
        
    }
    if (self.selectedTruckType == nil) {//没有历史数据
        //车型
        [self loadDataUnfold:NO AimData:self.truckTypesData WithInitialData:truckType];
        self.selectedTruckType = self.truckTypesData.firstObject;
        
    }else{//有
        [self loadDataUnfold:YES AimData:self.truckTypesData WithInitialData:truckType];
    }
    if (self.selectedGoodType == nil) {//没有有历史数据
        //货物类型
        [self loadDataUnfold:NO AimData:self.goodsTypeData WithInitialData:GoodsType];
        self.selectedGoodType = self.goodsTypeData.firstObject;
        
    }else{//有
        [self loadDataUnfold:YES AimData:self.goodsTypeData WithInitialData:GoodsType];
    }
    [self.collectionView reloadData];
    //MARK：初始值
    [self loadHistorySelectedLengths];
    [self loadHistorySelectedTruckType];
    [self loadHistorySelectedGoodsType];
    
    [self.collectionView reloadData];
}
- (void)reloadInitData{
    self.isLengthOpen = NO;
    //section 数据
    self.headerData = @[[HTTruckHeaderModel truckHeaderModelWithTitle:@"车长" detial:@"" type:0],[HTTruckHeaderModel truckHeaderModelWithTitle:@"车型" detial:@"" type:1],[HTTruckHeaderModel truckHeaderModelWithTitle:@"货物类型" detial:@"" type:1],[HTTruckHeaderModel truckHeaderModelWithTitle:@"只看零担货源" detial:@"" type:2]];
    [self reloadContentData];
   
}
//加载row的数据
- (void)loadDataUnfold:(BOOL)unfold AimData:(NSMutableArray *)aimData WithInitialData:(NSArray*)initialData{
    if (aimData==nil) {
        aimData = [NSMutableArray array];
    }
    if (initialData == nil) {
        return;
    }
    if (unfold) {//展开
        [aimData removeAllObjects];
        NSInteger index = 0;
        [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:@"不限" isSelected:NO TruckTypeModelType:TruckTypeModelTypeUnlimited index:index]];
        index ++;
        for (int i = 0; i < initialData.count; i++) {
            [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:initialData[i] isSelected:NO TruckTypeModelType:TruckTypeModelTypeDefault index:index]];
            index++;
        }
        if (aimData == self.lengthsData) {
            if (!([HTMUserDefaultUtil getHistoryLength] == nil || [HTMUserDefaultUtil getHistoryLength].length <= 0)) {
                [self.lengthsData addObject:[HTTruckTypeModel truckTypeModelWithTitle:[HTMUserDefaultUtil getHistoryLength] isSelected:NO TruckTypeModelType:TruckTypeModelTypeDefault index:index]];
            }
            index++;
        }
       
    }else{//关闭
        [aimData removeAllObjects];
        NSInteger index = 0;
        [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:@"不限" isSelected:NO TruckTypeModelType:TruckTypeModelTypeUnlimited index:index]];
        index ++;
        if (aimData == self.truckTypesData) {
            [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:initialData[0] isSelected:NO TruckTypeModelType:TruckTypeModelTypeDefault index:index]];
            index ++;
           [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:initialData[1] isSelected:NO TruckTypeModelType:TruckTypeModelTypeDefault index:index]];
            index++;
        }else{
            for (int i = 0; i < initialData.count; i++) {
                
                if (i > 2 && i<initialData.count - 3) {
                    continue;
                }
                [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:initialData[i] isSelected:NO TruckTypeModelType:TruckTypeModelTypeDefault index:index]];
                index++;
            }
        }
        [aimData addObject:[HTTruckTypeModel truckTypeModelWithTitle:@"更多" isSelected:NO TruckTypeModelType:TruckTypeModelTypeMore index:index]];
    }
}
- (NSMutableArray *)selectedLengths{
    if (!_selectedLengths) {
        _selectedLengths = [NSMutableArray array];
    }
    return _selectedLengths;
}
- (NSMutableArray *)lengthsData{
    if (!_lengthsData) {
        _lengthsData = [NSMutableArray array];
    }
    return _lengthsData;
}
- (NSMutableArray *)truckTypesData{
    if (!_truckTypesData) {
        _truckTypesData = [NSMutableArray array];
    }
    return _truckTypesData;
}
- (NSMutableArray *)goodsTypeData{
    if (!_goodsTypeData) {
        _goodsTypeData = [NSMutableArray array];
    }
    return _goodsTypeData;
}
#pragma mark --- 点击事件
//确定
- (IBAction)didClickConformBtn:(UIButton *)sender {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didClickConformWithLengths:TruckType:GoodType:isLessThanTruck:)]) {
        [self.delegate didClickConformWithLengths:self.selectedLengths TruckType:self.selectedTruckType GoodType:self.selectedGoodType isLessThanTruck:self.isLessThanTruck];
    }
    
}
//只看零担货源
- (void)headViewWithChosed:(BOOL)chosed{
    self.isLessThanTruck = chosed;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    HTTruckCollectionCell *cell = [self getCellIndexPath:indexPath];
    if (cell.truckTypeModel.truckTypeModelType == TruckTypeModelTypeMore) {
        //点击了更多
        [self moreCellEvent:indexPath collectionView:collectionView];
        return;
    }
    switch (indexPath.section) {
        case 0://车长
        {
            if (cell.truckTypeModel.truckTypeModelType == TruckTypeModelTypeUnlimited) {//不限
                for (HTTruckTypeModel *model in self.selectedLengths) {
                    HTTruckCollectionCell *lastCell =[self getCellIndexPath:[NSIndexPath indexPathForRow:model.index inSection:indexPath.section]];
                    lastCell.isChosed = NO;
                }
                cell.isChosed = YES;
                [self.selectedLengths removeAllObjects];
                [self.selectedLengths addObject:self.lengthsData.firstObject];
                
                
            }else{//普通
                if (self.selectedLengths.count >= 5 && !cell.isChosed) {
                    [HTShowUtil showMessage:@"最多选择5个车长"];
                    return;
                }
                cell.isChosed = !cell.isChosed;
                if (cell.isChosed) {//选中
                    //如果包含不限，就删除不限
                    if ([self.selectedLengths containsObject:self.lengthsData.firstObject]) {
                        HTTruckCollectionCell *lastCell = [self getCellIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];
                        lastCell.isChosed = NO;
                        [self.selectedLengths removeObject:self.lengthsData.firstObject];
                    }
                    
                    if (!([self.selectedLengths containsObject:self.lengthsData[indexPath.row]])) {
                        [self.selectedLengths addObject:self.lengthsData[indexPath.row]];
                    }
                }else{//取消选中
                    if ([self.selectedLengths containsObject:self.lengthsData[indexPath.row]]) {
                        [self.selectedLengths removeObject:self.lengthsData[indexPath.row]];
                    }
                    //如果选中的数据为空，就添加不限
                    if (self.selectedLengths.count <= 0) {
                        HTTruckCollectionCell *lastCell = [self getCellIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];
                        lastCell.isChosed = YES;
                        [self.selectedLengths addObject:self.lengthsData.firstObject];
                    }
                }
            }
        }
            break;
        case 1://车型
        {
            if (cell.truckTypeModel.truckTypeModelType == TruckTypeModelTypeUnlimited) {//不限
                if (self.selectedTruckType) {
                    HTTruckCollectionCell *lastCell = (HTTruckCollectionCell *)self.selectedTruckType.cell;
                    lastCell.isChosed = NO;
                }
                cell.isChosed = YES;
                self.selectedTruckType = cell.truckTypeModel;
            }else{//普通
                cell.isChosed = !cell.isChosed;
                if (cell.isChosed) {
                    if (self.selectedTruckType) {
                        HTTruckCollectionCell *lastCell = (HTTruckCollectionCell *)self.selectedTruckType.cell;
                        lastCell.isChosed = NO;
                    }
                    self.selectedTruckType = cell.truckTypeModel;
                }else{
                    self.selectedTruckType = self.truckTypesData.firstObject;
                    HTTruckCollectionCell *curCell = ( HTTruckCollectionCell *)self.selectedTruckType.cell;
                    curCell.isChosed = YES;
                }
            }
        }
            break;
        case 2://货物类型
        {
            if (cell.truckTypeModel.truckTypeModelType == TruckTypeModelTypeUnlimited) {//不限
                if (self.selectedGoodType) {
                    HTTruckCollectionCell *lastCell =(HTTruckCollectionCell *)self.selectedGoodType.cell;
                    lastCell.isChosed = NO;
                }
                cell.isChosed = YES;
                self.selectedGoodType = cell.truckTypeModel;
            }else{//普通
                cell.isChosed = !cell.isChosed;
                if (cell.isChosed) {
                    if (self.selectedGoodType) {
                        HTTruckCollectionCell *lastCell = (HTTruckCollectionCell *)self.selectedGoodType.cell;
                        lastCell.isChosed = NO;
                    }
                    self.selectedGoodType = cell.truckTypeModel;
                }else{
                    self.selectedGoodType = self.goodsTypeData.firstObject;
                    HTTruckCollectionCell *curCell = [self getCellIndexPath:[NSIndexPath indexPathForRow:self.selectedGoodType.index inSection:indexPath.section]];
                    curCell.isChosed = YES;
                }
            }
        }
            break;
        default:
            break;
    }
}
//获取cell
- (HTTruckCollectionCell *)getCellIndexPath:(NSIndexPath *)indexPath{
   HTTruckCollectionCell *cell = (HTTruckCollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    if (cell == nil) {
        [self.collectionView layoutIfNeeded];
        cell = (HTTruckCollectionCell *) [self.collectionView cellForItemAtIndexPath:indexPath];
    }
    return cell;
}

//加载历史选择的长度
- (void)loadHistorySelectedLengths{
    NSArray *selected = [NSArray arrayWithArray:self.selectedLengths];
    [self.selectedLengths removeAllObjects];
    for (HTTruckTypeModel *selectedModel in selected) {
        for (HTTruckTypeModel *model in self.lengthsData) {
            if ([selectedModel.title isEqualToString:model.title]) {
                model.isSelected = YES;
                [self.selectedLengths addObject:model];
                break;
            }
        }
    }
}
- (void)loadHistorySelectedTruckType{
    for (HTTruckTypeModel *model in self.truckTypesData) {
        if ([self.selectedTruckType.title isEqualToString:model.title]) {
            model.isSelected = YES;
            self.selectedTruckType = model;
            break;
        }
    }
}
- (void)loadHistorySelectedGoodsType{
    for (HTTruckTypeModel *model in self.goodsTypeData) {
        if ([self.selectedGoodType.title isEqualToString:model.title]) {
            model.isSelected = YES;
            self.selectedGoodType = model;
            break;
        }
    }
}
//点击了更多
- (void)moreCellEvent:(NSIndexPath *)indexPath collectionView:(UICollectionView *)collectionView{
    NSArray *GoodsType =  self.plistData[@"GoodsType"];
    NSArray *lengths =  self.plistData[@"TruckLength"];
    NSArray *truckType =  self.plistData[@"TruckType"];
    switch (indexPath.section) {
        case 0://车长
        {
            self.isLengthOpen = YES;
            [self loadDataUnfold:YES AimData:self.lengthsData WithInitialData:lengths];
            [self loadHistorySelectedLengths];
            [collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        }
            break;
        case 1://车型
        {
            [self loadDataUnfold:YES AimData:self.truckTypesData WithInitialData:truckType];
            [self loadHistorySelectedTruckType];
            [collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
        }
            break;
        case 2://货物类型
        {
            [self loadDataUnfold:YES AimData:self.goodsTypeData WithInitialData:GoodsType];
            [self loadHistorySelectedGoodsType];
            [collectionView reloadSections:[NSIndexSet indexSetWithIndex:2]];
        }
            break;
        default:
            break;
    }
}
#pragma mark -- collectionViewDelegate & Datasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    switch (section) {
        case 0://车长
        {
            return  self.lengthsData.count;
        }
            break;
        case 1://车型
        {
            return self.truckTypesData.count;
        }
            break;
        case 2://货物类型
        {
            return self.goodsTypeData.count;
        }
            break;
        case 3://只看零担货源
        {
            return 0;
        }
            break;
        default: return 0;
            break;
    }
    return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kHTScreenWidth, 60);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == 0 && _isLengthOpen ) {
        return  CGSizeMake(kHTScreenWidth, kWidth(30));
    }else{
        return CGSizeZero;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HTTruckCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:TruckCollectionCell forIndexPath:indexPath];
    switch (indexPath.section) {
        case 0:
        {
            cell.truckTypeModel = self.lengthsData[indexPath.row];
        }
            break;
         case 1:
        {
            cell.truckTypeModel = self.truckTypesData[indexPath.row];
        }
            break;
         case 2:
        {
            cell.truckTypeModel = self.goodsTypeData[indexPath.row];
        }
            break;
        default:
            break;
    }
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        HTHeaderCollectionView *headReusableView=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderCollectionView forIndexPath:indexPath];
        headReusableView.headerModel = self.headerData[indexPath.section];
        headReusableView.isSelectedOn = self.isLessThanTruck;
        __weak typeof(self) weakSelf = self;
        headReusableView.headerViewBlock = ^(BOOL chosed) {
            [weakSelf headViewWithChosed:chosed];
        };
        reusableView = headReusableView;
    }
   
    if (kind == UICollectionElementKindSectionFooter)
    {
        if (indexPath.section == 0) {
            HTTextFieldFooterView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:TextFieldFooter forIndexPath:indexPath];
            self.textField = footerview.myTextField;
            self.textField.delegate = self;
            self.textField.keyboardType = UIKeyboardTypeNumberPad;
            UIToolbar * toobar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 38.0f)];
            toobar.translucent = YES;
            toobar.barStyle = UIBarStyleDefault;
            UIBarButtonItem * spaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"完成" forState:UIControlStateNormal];
            [button setTitleColor:kBlueColor forState:UIControlStateNormal];
            [button addTarget:self action:@selector(resignKeyboard:) forControlEvents:UIControlEventTouchUpInside];
            UIBarButtonItem *doneBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
            [toobar setItems:@[spaceBarButtonItem,doneBarButtonItem]];
            _textField.inputAccessoryView = toobar;
            reusableView = footerview;
        }
    }
    return reusableView;
}

#pragma mark --- 监听键盘
- (void)resignKeyboard:(id)sender{
    [_textField resignFirstResponder];
}
/**
 * 键盘的frame发生改变时调用（显示、隐藏等）
 */
- (void)keyboardWillShowOrHide:(NSNotification *)notification
{
    //    //获取通知名
    NSString *notificationName = notification.name;
    
    if ([notificationName isEqualToString:UIKeyboardWillShowNotification]) {
        NSDictionary *keyboardInfo = notification.userInfo;
        CGRect keyboardF = [keyboardInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGRect fra = [self convertRect:keyboardF fromView:nil];
        CGFloat keyboardHeight = fra.size.height;
        
        CGRect selfFrameFromUIWindow = [self.textField convertRect:self.textField.bounds toView:nil];
        // textField底部距离屏幕底部的距离
        CGFloat bottomHeight =kHTScreenHeight - selfFrameFromUIWindow.origin.y - selfFrameFromUIWindow.size.height;
        CGFloat off =keyboardHeight - bottomHeight + 10;
        if(off > 0)
            
        {
            self.off = off;
            CGPoint oldPoint = self.collectionView.contentOffset;
            CGPoint scrollPoint = CGPointMake(0.0 + oldPoint.x, off + oldPoint.y);
            [self.collectionView setContentOffset:scrollPoint animated:YES];
            
        }
    }
    if ([notificationName isEqualToString:UIKeyboardWillHideNotification]) {
        if (self.off > 0) {
            CGPoint oldPoint = self.collectionView.contentOffset;
            CGPoint scrollPoint = CGPointMake(oldPoint.x - 0.0, oldPoint.y - _off);
            [self.collectionView setContentOffset:scrollPoint animated:YES];
            self.off = 0;
        }
    }
}
- (void)keyboardHide:(NSNotification *)notification{
         NSString *length = self.textField.text;
        if (length == nil || length.length <= 0) {
            return;
        }
        if ([length floatValue] > 20.0) {
            [HTShowUtil showMessage:@"车长不超过20米"];
            return;
        }
        if (self.selectedLengths.count >= 5) {
            [HTShowUtil showMessage:@"最多选择5个车长"];
        }else{
            BOOL isContain = NO;
            for (HTTruckTypeModel *model in self.lengthsData) {
                if (model.title.floatValue == length.floatValue) {
                    model.isSelected = YES;
                    if (![self.selectedLengths containsObject:model]) {
                        [self.selectedLengths addObject:model];
                    }
                    isContain = YES;
                    break;
                }
            }
            if (isContain == NO) {
                NSString *history = [HTMUserDefaultUtil getHistoryLength];
                for (HTTruckTypeModel *model in self.selectedLengths) {
                    if (model.title.floatValue == history.floatValue) {
                        [self.selectedLengths removeObject:model];
                    }
                }
                [HTMUserDefaultUtil saveHistoryLength:length];
                NSArray *lengths =  self.plistData[@"TruckLength"];
                [self loadDataUnfold:YES AimData:self.lengthsData WithInitialData:lengths];
                [self loadHistorySelectedLengths];
                for (HTTruckTypeModel *model in self.lengthsData) {
                    NSString *first =  [NSString stringWithFormat:@"%.2f",model.title.floatValue];
                    NSString *second =  [NSString stringWithFormat:@"%.2f",length.floatValue];
                    if ([first isEqualToString:second]) {
                        model.isSelected = YES;
                        if (![self.selectedLengths containsObject:model]) {
                            [self.selectedLengths addObject:model];
                        }
                        break;
                    }
                }
            }
            self.textField.text = @"";
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    if(textField == self.textField)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            return NO;
        }
    }
    return YES;
}


#pragma mark --- 显示&隐藏
-(void)showView{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:.3 animations:^{
       
        [self layoutIfNeeded];
    }];
}
-(void)dismissView {
    
    [UIView animateWithDuration:.3 animations:^{
        self.bottomView.alpha = 0;
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self removeFromSuperview];
    }];
}






@end
